<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>人物列表</title>
    <link rel="stylesheet" href="/bootstrap.min.css">
    <style>
        .modal-dialog {
            max-width: 500px;
        }

        /* 基础样式 */
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
        }

        button {
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        button:hover {
            background-color: #45a049;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }

        th {
            background-color: #f2f2f2;
        }

        tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        .download-btn {
            background-color: #2196F3;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.9em;
        }

        .download-btn:hover {
            background-color: #1976D2;
        }
    </style>
</head>
<body>

<div class="container mt-5">
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#uploadModal">
        上传文件
    </button>

    <div class="row mt-3">
        <div class="col">
            <ul class="list-group">
                <li class="list-group-item" th:each="person : ${persons}" th:text="${person.name}"></li>
            </ul>
        </div>
    </div>
</div>
<div class="container">
    <h2>数据查询</h2>
    <button onclick="fetchData({})">查询数据</button>

    <table id="dataTable">
        <thead>
        <tr>
            <th>名称</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <!-- 数据将通过JavaScript动态填充 -->
        </tbody>
    </table>
</div>
<!-- Modal -->
<div class="modal fade" id="uploadModal" tabindex="-1" role="dialog" aria-labelledby="uploadModalLabel"
     aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="uploadModalLabel">上传文件</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="uploadForm" enctype="multipart/form-data">
                    <div class="form-group">
                        <label for="fileInput">选择文件</label>
                        <input type="file" class="form-control-file" id="fileInput" name="file" accept=".mp4,.ts">
                    </div>
                    <div class="form-group">
                        <label for="filepath">输入文件路径</label>
                        <input type="text" class="form-control" id="filepath" name="name" placeholder="请输入名称">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="submitForm()">提交</button>
            </div>
        </div>
    </div>
</div>

<script src="/jquery-3.5.1.slim.min.js"></script>
<script src="/popper.min.js"></script>
<script src="/bootstrap.min.js"></script>
<script>
    function fetchData(queryParams) {
        let flg = false;
        const date = queryParams.date || ''; // 获取search参数，默认为空字符串
        console.log(date)
        if (date == '') {
            flg = true
        }
        const apiUrl = `/api/gateway/demo/result?date=${date}`;
        // 显示加载提示
        const tbody = document.querySelector('#dataTable tbody');
        tbody.innerHTML = '<tr><td colspan="4">加载中...</td></tr>';

        // 使用Fetch API获取数据
        fetch(apiUrl, {
            method: 'GET'
        })
            .then(response => response.json())
            .then(data => {
                // 清空加载提示
                tbody.innerHTML = '';

                // 动态生成表格行
                data.data.forEach(item => {
                    const row = document.createElement('tr');
                    if(flg){
                        row.innerHTML = `
                            <td>${item.filename}</td>
                            <td><button onclick="fetchData({ date: '${item.filename}' })">查询当前月份的数据</button></td>
                        `;
                    }else {
                        row.innerHTML = `
                            <td>${item.filename}</td>
                            <td>
                            <button onclick="downloadData({ name: '${item.filename}', path : '${item.filepath}' })">下载</>
                            </td>
                        `;
                    }

                    tbody.appendChild(row);
                });
            })
            .catch(error => {
                tbody.innerHTML = '<tr><td colspan="4">数据加载失败</td></tr>';
                console.error('Error:', error);
            });
    }
    function downloadData(queryParams) {
        console.info(queryParams)
        const path = queryParams.path || ''; // 获取search参数，默认为空字符串
        const name = queryParams.name || '';
        const apiUrl = `/api/gateway/demo/download?path=${path}`;

        fetch(apiUrl)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`文件下载失败，状态码：${response.status}`);
                }
                return response.blob();
            })
            .then(blob => {
                // 创建虚拟链接并触发下载
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = name; // 根据实际情况设置文件名
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
            })
            .catch(error => {
                alert(`下载失败：${error.message}`);
            });
    }

    function submitForm() {
        var formData = new FormData(document.getElementById('uploadForm'));
        fetch('/api/gateway/demo/upload', {
            method: 'POST',
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                alert('文件解析成功，结果如下: ' + data.data);
                $('#uploadModal').modal('hide');
            })
            .catch(error => {
                alert('文件上传失败: ' + error);
            });
    }
</script>
</body>
</html>